<!-- 培训项目 -->
<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
        >
            <el-form-item label="培训名称" prop="varName">
                <el-input
                    v-model="queryParams.projectName"
                    placeholder="请输入"
                    clearable
                    size="small"
                />
            </el-form-item>
            <el-form-item label="培训类型" prop="typeId">
                <el-select
                    v-model="queryParams.projectType"
                    placeholder="请选择"
                    :style="{ width: '100%' }"
                >
                    <el-option
                        v-for="item in projectTypeOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-table
            v-loading="loading"
            :data="projectList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
                label="培训名称"
                align="center"
                prop="projectName"
            />
            <el-table-column
                label="培训类型"
                align="center"
                prop="projectType"
            />
            <el-table-column
                label="项目时间(开始)"
                align="center"
                prop="projectStartTime"
            />
            <el-table-column
                label="项目时间(结束)"
                align="center"
                prop="projectEndTime"
            />
            <el-table-column label="培训状态" align="center" prop="">
                <template slot-scope="scope">
                    {{
                        scope.row.projectState === 0
                            ? "未开始"
                            : scope.row.projectState === 1
                            ? "进行中"
                            : "已结束"
                    }}
                </template>
            </el-table-column>
            <el-table-column label="考试次数" align="center" prop="examNum" />
            <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="selectDetailt(scope.row)"
                        >详情</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="uploadImg(scope.row)"
                        >图片上传</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改课程对话框 -->
        <el-dialog
            :title="title"
            :before-close="closeDialog"
            :visible.sync="open"
            width="800px"
            append-to-body
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <el-form-item label="培训名称" prop="projectName">
                    <el-input
                        v-model="form.projectName"
                        placeholder="请输入培训名称"
                    />
                </el-form-item>
                <el-form-item label="培训类型" prop="projectType">
                    <el-select
                        v-model="form.projectType"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in projectTypeOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="考试次数" prop="examNum">
                    <el-input
                        v-model="form.examNum"
                        placeholder="请输入考试次数"
                    />
                </el-form-item>
                <el-form-item label="培训时间" prop="trainTime">
                    <el-date-picker
                        v-model="form.trainTime"
                        type="datetimerange"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="考试时间" prop="examTime">
                    <el-date-picker
                        v-model="form.examTime"
                        type="datetimerange"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="课程选择" prop="inDate">
                    <el-button
                        v-if="butShow"
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="courseopen = true"
                        >选择课程</el-button
                    >
                    <el-table
                        v-loading="loading"
                        :data="CourseList"
                        style="height: 200px;overflow-y: auto;"
                    >
                        <el-table-column
                            label="课程名称"
                            align="center"
                            prop="varName"
                        />
                        <el-table-column
                            label="课程类别"
                            align="center"
                            prop="typeId"
                        />
                        <el-table-column
                            label="课程描述"
                            align="center"
                            prop="varDesc"
                        />
                        <el-table-column
                            label="学时"
                            align="center"
                            prop="intClassHour"
                        />
                        <el-table-column
                            label="试题数量"
                            align="center"
                            prop="questionCount"
                        />
                        <el-table-column
                            label="试用行业"
                            align="center"
                            prop="varIndustry"
                        />
                    </el-table>
                </el-form-item>
                <el-form-item label="人员选择" prop="inDate">
                    <el-button
                        v-if="butShow"
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="useropen = true"
                        >选择人员</el-button
                    >
                    <el-table
                        v-loading="loading"
                        :data="UserList"
                        style="height: 200px;overflow-y: auto;"
                    >
                        <el-table-column
                            label="姓名"
                            align="center"
                            prop="nickName"
                        />
                        <el-table-column
                            label="单位"
                            align="center"
                            prop="dept.deptName"
                        />
                    </el-table>
                </el-form-item>
                <el-form-item label="培训内容" prop="remark">
                    <el-input type="textarea" v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <div v-if="butShow" slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 选择课程 -->
        <el-dialog
            title="选择课程"
            :visible.sync="courseopen"
            width="65%"
            append-to-body
        >
            <selectCourse @selectFn="selectCourseFn"></selectCourse>
        </el-dialog>
        <!-- 选择人员 -->
        <el-dialog
            title="选择人员"
            :visible.sync="useropen"
            width="65%"
            append-to-body
            :before-close="clearUploadFiles"
        >
            <selectUsers @selectFn="selectUserFn"></selectUsers>
        </el-dialog>
        <el-dialog
            title="培训图片上传"
            :visible.sync="uploadopen"
            width="510px"
            append-to-body
            class="uploadDialog"
        >
            <el-upload
                class="avatar-uploader"
                ref="uploadPhoto"
                :limit="limitImgNumber1"
                list-type="picture-card"
                :file-list="fileList1"
                accept=".png, .jpg"
                :headers="upload.headers"
                :on-remove="removeFile1"
                :action="upload.url"
                :on-change="handleFileChange1"
                :on-success="handleFileSuccess1"
                :class="{ hideAdd: uploadDisabled1 }"
            >
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addProjectPhoto"
                    >确 定</el-button
                >
                <el-button @click="clearUploadFiles">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listTrainProject, addTrainProject, addProjectPhoto, getProjectDetail } from "@/api/system/education";
import { getToken } from "@/utils/auth";
import selectCourse from '@/components/selectCourse'
import selectUsers from '@/components/selectUsers'
export default {
    name: "terminal_project",
    components: {
        selectCourse,
        selectUsers
    },
    data () {
        return {
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload"
            },
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 课程表格数据
            projectList: [],
            // 弹出层标题
            title: "",
            open: false,
            courseopen: false,
            uploadopen: false,
            useropen: false,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                projectName: '',
                projectType: '',
                projectMode: "1",
            },
            limitImgNumber: 1,
            limitImgNumber1: 3,
            // 表单参数
            form: {
                projectName: undefined,
                projectType: undefined,
                examNum: undefined,
                trainStartTime: undefined,
                trainEndTime: undefined,
                examStartTime: undefined,
                examEndTime: undefined,
                trainTime: undefined,
                examTime: undefined,
                courseList: [],
                personList: [],
                remark: undefined
            },
            // 表单校验
            rules: {
                projectName: [
                    { required: true, message: "请输入培训名称", trigger: ['blur', 'change'] }
                ],
                projectType: [
                    { required: true, message: "请选择培训类型", trigger: ['blur', 'change'] }
                ],
                examNum: [
                    { required: true, message: "请输入课考试次数", trigger: ['blur', 'change'] }
                ],
                trainTime: [
                    { required: true, message: "请选择培训时间", trigger: ['blur', 'change'] }
                ],
                examTime: [
                    { required: true, message: "请选择考试时间", trigger: ['blur', 'change'] }
                ],
                remark: { required: true, message: "请选择培训内容", trigger: ['blur', 'change'] }
            },
            fileList: [],
            fileList1: [],
            uploadDisabled: false,
            uploadDisabled1: false,
            projectTypeOptions: [], // 培训类别
            varIndustryOptions: [], // 适用行业
            chrCategoryOptions: [], // 试题类型
            CourseList: [],//课程列表
            UserList: [],//人员列表
            butShow: true,  //添加时显示
            projectPhotoList: [], // 项目图片
            projectId: ''
        };
    },
    created () {
        this.getList();
        this.getDicts("train_type").then(response => {
            this.projectTypeOptions = response.data;
        });
    },
    watch: {
        $route (to, from) {
            if (to.path === '/educationtrain/project') {
                this.getList();
            }
        }
    },
    methods: {
        closeDialog (done) {
            done()
        },
        removeFile (file, fileList) {
            this.handleFileChange(file, fileList)
        },
        handleFileChange (file, fileList) {
            this.uploadDisabled = fileList.length >= this.limitImgNumber;
        },
        removeFile1 (file, fileList) {
            this.handleFileChange1(file, fileList)
        },
        handleFileChange1 (file, fileList) {
            this.uploadDisabled1 = fileList.length >= this.limitImgNumber1;
        },
        handleFileSuccess (res) {
            this.form.varCoverInfo = res.url
        },
        handleFileSuccess1 (response, file, fileList) {
            this.projectPhotoList = fileList.map(item => {
                let url = item.response ? item.response.url : item.url
                return url
            })
        },
        dataFormat (val, options) {
            for (let i = 0; i < this[options].length; i++) {
                if (val == this[options][i].dictLabel) {
                    return this[options][i].dictValue
                }
            }
            return val
        },
        /** 查询课程列表 */
        getList () {
            if (this.loading) return false
            this.loading = true;
            listTrainProject(this.queryParams).then(response => {
                this.projectList = response.data;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.CourseList = [];
            this.UserList = [];
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                projectName: undefined,
                projectType: undefined,
                examNum: undefined,
                trainStartTime: undefined,
                trainEndTime: undefined,
                examStartTime: undefined,
                examEndTime: undefined,
                trainTime: undefined,
                examTime: undefined,
                courseList: [],
                personList: [],
                remark: undefined
            };
            this.CourseList = [];
            this.UserList = [];
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.queryParams.projectName = "";
            this.queryParams.projectType = "";
            // this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.butShow = true;
            this.open = true;
            this.title = "添加培训项目";
        },
        /** 提交按钮 */
        submitForm: function () {
            this.form.personList = []
            this.form.courseList = []
            let params = Object.assign({}, this.form)
            this.$refs["form"].validate(valid => {
                if (valid) {
                    //时间
                    params.trainStartTime = this.form.trainTime[0];
                    params.trainEndTime = this.form.trainTime[1];
                    params.examStartTime = this.form.examTime[0];
                    params.examEndTime = this.form.examTime[1];
                    //课程
                    for (let i = 0; i < this.CourseList.length; i++) {
                        let cobj = {
                            'id': this.CourseList[i].id,
                            'questionCount': this.CourseList[i].questionCount,
                        };
                        params.courseList.push(cobj);
                    }
                    //人员
                    for (let i = 0; i < this.UserList.length; i++) {
                        let uobj = {
                            'userId': this.UserList[i].userId
                        };
                        params.personList.push(uobj);
                    }
                    // console.log(this.form);

                    if (params.courseList.length == 0) {
                        this.$message.error('请选择课程')
                        return;
                    }
                    if (params.personList.length == 0) {
                        this.$message.error('请选择人员')
                        return;
                    }

                    addTrainProject(params).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }
                    });
                }
            });
        },
        selectCourseFn (selectedIds, clearSelected) { // 添加课程回调
            if (selectedIds.length == 0) {
                this.$message.error('请选择课程')
            } else {
                //  console.log(selectedIds)
                this.CourseList = selectedIds;
                this.courseopen = false
                clearSelected() // 清除选中的table状态
            }
        },
        selectUserFn (selectedIds, clearSelected) { // 添加人员回调
            if (selectedIds.length == 0) {
                this.$message.error('请选择人员')
            } else {
                // console.log(selectedIds)
                this.UserList = selectedIds;
                clearSelected() // 清除选中的table状态
                this.useropen = false
            }
        },
        selectDetailt (item) {
            this.reset();
            this.butShow = false;
            this.open = true;
            this.title = "培训项目详情";
            this.getProjectDetail(item.projectId)
        },
        // 培训类型字典翻译
        trainTypeFormat (projectType) {
            for (let i = 0; i < this.projectTypeOptions.length; i++) {
                if (projectType == this.projectTypeOptions[i].dictLabel) {
                    return this.projectTypeOptions[i].dictValue;
                }
            }
        },
        uploadImg (item) {
            this.uploadopen = true
            this.projectId = item.projectId
            this.fileList1 = item.photos.map(item => {
                return {
                    url: item
                }
            })
            this.uploadDisabled1 = this.fileList1.length >= this.limitImgNumber;
        },
        addProjectPhoto () {
            let params = {
                projectId: this.projectId,
                paths: this.projectPhotoList
            }
            addProjectPhoto(params).then((res) => {
                if (res.code === 200) {
                    this.msgSuccess("图片上传成功");
                    this.handleQuery()
                    this.clearUploadFiles()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        clearUploadFiles (done) {
            this.$refs.uploadPhoto.clearFiles()
            this.uploadDisabled1 = false
            this.uploadopen = false
            if (typeof done === 'function') done()
        },
        getProjectDetail (projectId) {
            let params = {
                'projectId': projectId
            }
            getProjectDetail(params).then(res => {
                let item = res.data
                this.form.projectName = item.projectName;
                //培训类型翻译
                this.form.projectType = this.trainTypeFormat(item.projectType);
                this.form.examNum = item.examNum;
                //时间
                this.form.trainTime = [];
                this.form.trainTime[0] = item.trainStartTime;
                this.form.trainTime[1] = item.trainEndTime;
                this.form.examTime = [];
                this.form.examTime[0] = item.examStartTime;
                this.form.examTime[1] = item.examEndTime;
                //课程
                this.CourseList = item.courseList;
                //人员 - 处理返回字段不一样问题
                let ulist = item.personList;
                for (let i = 0; i < ulist.length; i++) {
                    let uobj = {
                        'nickName': ulist[i].userName,
                        'dept': {
                            'deptName': ulist[i].deptName
                        }
                    };
                    this.UserList.push(uobj);
                }
                this.form.remark = item.remark;
            })
        }
    }
};
</script>
<style scoped>
.varCoverInfo {
    max-width: 100px;
    max-height: 100px;
}
</style>
